package smecta.client.print.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.Button;
import javafx.scene.control.ChoiceBox;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import smecta.client.print.common.constants.PrintConstant;
import smecta.client.print.domain.ScpSysSettings;
import smecta.client.print.service.ScpSysSettingsService;
import smecta.client.print.util.AlertUtil;

import javax.print.PrintServiceLookup;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

@Slf4j
@Component
public class PrintSettingController {

    @Autowired
    private ScpSysSettingsService scpSysSettingsService;
    @FXML
    private ChoiceBox<String> generalBoxPrinter;

    @FXML
    private ChoiceBox<String> barcodeBoxPrinter;

    @FXML
    private ChoiceBox<String> generalCodePrinter;

    @FXML
    private ChoiceBox<String> otherPrinters;

    @FXML
    private VBox settingBox;

    @FXML
    private Button btnCancel;

    private Properties properties = new Properties();

    @FXML
    private TextField filePathFieldBox;

    @FXML
    private Button browseButtonBox;

    @FXML
    private TextField filePathFieldCode;

    @FXML
    private Button browseButtonCode;

    // 初始化方法
    public void initialize() {
        // 扫描当前机器上的所有打印外设
        ObservableList<String> options = FXCollections.observableArrayList(findAllPrintService());
        generalBoxPrinter.setItems(options);
        barcodeBoxPrinter.setItems(options);
        generalCodePrinter.setItems(options);
        otherPrinters.setItems(options);

        // 填充历史保存的打印机
        loadFromDB();
        generalBoxPrinter.setValue(properties.getProperty("generalBoxPrinter", ""));
        barcodeBoxPrinter.setValue(properties.getProperty("barcodeBoxPrinter", ""));
        generalCodePrinter.setValue(properties.getProperty("generalCodePrinter", ""));
        otherPrinters.setValue(properties.getProperty("otherPrinters", ""));
        filePathFieldBox.setText(properties.getProperty("filePathFieldBox", ""));
        filePathFieldCode.setText(properties.getProperty("filePathFieldCode", ""));
    }

    @FXML
    private void handleBrowseBox(ActionEvent event) {
        File file = new File(filePathFieldBox.getText());
        FileChooser fileChooser = new FileChooser();
        // 如果文本框已经有值且该路径存在，则直接打开文件夹
        if (file.exists()) {
            try {
                fileChooser.setInitialDirectory(new File(file.getAbsoluteFile().getParent()));
            } catch (Exception e) {
                // 处理异常
                log.error("handleBrowseBox error:{}", e);
            }
        }
        File selectedFile = fileChooser.showOpenDialog(browseButtonBox.getScene().getWindow());
        if (selectedFile != null) {
            filePathFieldBox.setText(selectedFile.getAbsolutePath());
        }
    }

    @FXML
    private void handleBrowseCode(ActionEvent event) {
        File file = new File(filePathFieldCode.getText());
        FileChooser fileChooser = new FileChooser();
        // 如果文本框已经有值且该路径存在，则直接打开文件夹
        if (file.exists()) {
            try {
                fileChooser.setInitialDirectory(new File(file.getAbsoluteFile().getParent()));
            } catch (Exception e) {
                // 处理异常
                log.error("handleBrowseCode error:{}", e);
            }
        }
        File selectedFile = fileChooser.showOpenDialog(filePathFieldCode.getScene().getWindow());
        if (selectedFile != null) {
            filePathFieldCode.setText(selectedFile.getAbsolutePath());
        }
    }

    private static List<String> findAllPrintService() {
        List<String> printers = new ArrayList<>();
        javax.print.PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
        for (javax.print.PrintService printService : printServices) {
            printers.add(printService.toString());
        }
        return printers;
    }

    public Properties loadFromDB() {
        ScpSysSettings setting = scpSysSettingsService.findByKey(PrintConstant.DB_DICT_KEY);
        if (Objects.isNull(setting)) {
            return properties;
        }
        Properties currentProp = JSONObject.parseObject(setting.getSettingValue(), Properties.class);
        properties = currentProp;
        return properties;
    }

    @FXML
    private void handleSave() {
        properties.setProperty("generalBoxPrinter", generalBoxPrinter.getValue());
        properties.setProperty("barcodeBoxPrinter", barcodeBoxPrinter.getValue());
        properties.setProperty("generalCodePrinter", generalCodePrinter.getValue());
        properties.setProperty("otherPrinters", otherPrinters.getValue());
        properties.setProperty("filePathFieldBox", filePathFieldBox.getText());
        properties.setProperty("filePathFieldCode", filePathFieldCode.getText());
        scpSysSettingsService.updateKeyOrInit(PrintConstant.DB_DICT_KEY, JSON.toJSONString(properties));
        AlertUtil.infoFinishAutoClose("保存成功", 3000L);
    }

    @FXML
    private void handleCancel() {
        Stage stage = (Stage) btnCancel.getScene().getWindow();
        stage.close();
    }
}
